package org.csu.jpetstore_front.controller.front;

import org.csu.jpetstore_front.common.CommonResponse;
import org.csu.jpetstore_front.common.ResponseCode;
import org.csu.jpetstore_front.entity.Account;
import org.csu.jpetstore_front.node.PassToken;
import org.csu.jpetstore_front.service.AccountService;
import org.csu.jpetstore_front.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/accounts")
@CrossOrigin
public class AccountController {

    @Autowired
    private AccountService accountService;

    @PassToken
    @PostMapping("/login")
    @ResponseBody
    public CommonResponse<AccountVO> login(@RequestBody AccountVO accountVO, HttpSession session){
        System.out.println(accountVO.getUsername());
        System.out.println(session.getAttribute("checkcode"));
        if (session.getAttribute("checkcode")==null)
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "缺少验证码");

        if (session.getAttribute("checkcode").equals(accountVO.getCheckcode()))
        {
            return accountService.login(accountVO);
        }
        return CommonResponse.createForError(ResponseCode.ERROR.getCode(),"验证码错误");
    }

    @PassToken
    @PostMapping("/register")
    @ResponseBody
    public CommonResponse<AccountVO> register(@RequestBody AccountVO accountVO)
    {
        return accountService.register(accountVO);
    }

    @GetMapping("/{username}")
    @ResponseBody
    public CommonResponse<AccountVO> findAccount(@PathVariable("username") String username){
        return accountService.findAccount(username);
    }


    //检查用户名是否可用
    @GetMapping("/inspection/{username}")
    @ResponseBody
    public CommonResponse<String> checkUsernameIsExists(@PathVariable("username") String username)
    {
        return accountService.checkUsernameIsExists(username);
    }



    @PutMapping("")
    @ResponseBody
    public CommonResponse<AccountVO> changeAccountInformation(@RequestBody AccountVO accountVO)
    {
        return accountService.changeAccountInformation(accountVO);
    }

    @GetMapping("/demo")
    @ResponseBody
    public CommonResponse<AccountVO> test(AccountVO accountVO){
        return CommonResponse.createForSuccessMessage("拦截器成功");
    }
}
